import re

from django.contrib.auth.backends import ModelBackend


#重写结果返回,默认返回token
from users.models import User


def jwt_response_payload_handler(token,user=None,request=None):
    return {
        'token':token,
        'username':user.username,
        'user_id':user.id
    }

#默认验证登陆只支持用户名,重写使之支持手机号登陆
class UsernameMobileAuthBackend(ModelBackend):
    #父类提供的方法
    def authenticate(self, request, username=None, password=None, **kwargs):

        #正则判断穿进来的username
        try:
            if re.match(r'1[3-9]\d{9}$',username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None

        if user is not None and user.check_password(password):
            return user


